package com.inzone.fram.gray.config;

import com.inzone.fram.gray.common.rule.MatchingContext;
import feign.RequestInterceptor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 给Feign添加灰度头
 * @author 丁常磊
 * @date 2021/10/15 19:29
 */
@ConditionalOnClass({
        RequestInterceptor.class
})
@Configuration
public class MatchingInitFeignConfig {

    @Bean
    public RequestInterceptor requestInterceptor() {
        return requestTemplate -> {
            if (MatchingContext.isInitialized()) {
                MatchingContext current = MatchingContext.current();
                String tagsText = current.getTagsText();

                if (tagsText != null) {
                    requestTemplate.header(MatchingContext.GRAY_HEADER_TAGS, tagsText);
                }

                String groupsText = current.getGroupsText();
                if (groupsText != null) {
                    requestTemplate.header(MatchingContext.GRAY_HEADER_GROUPS, groupsText);
                }
            }
        };
    }

}
